package com.sgcc.pda.ssal.mqtt.proxy.server;

import android.os.SystemClock;
import android.util.Log;

import com.hzwq.codec.client.EncryptListener;
import com.hzwq.codec.config.SSALConfigInitProperties;
import com.hzwq.codec.entity.impl.DefaultSSALParser;
import com.hzwq.codec.entity.impl.SSALMessage;
import com.hzwq.codec.enums.FCCodeBinEnum;
import com.hzwq.codec.enums.UserContentTypeOctEnum;
import com.hzwq.codec.util.ByteTools;
import com.sgcc.pda.mdrh.app.ZoomApplication;
import com.sgcc.pda.ssal.mqtt.proxy.client.MqttProxyClient;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by cj on 2020/1/10.
 * 收到paho请求时，组装ssal报文
 * 通过代理client的channel写出去。
 */
public class MqttServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private static final String TAG = "mqtt";

    private String businessIdHex = null;
    private EncryptListener encryptListener;

    public MqttServerHandler(EncryptListener encryptListener) {
        this.encryptListener = encryptListener;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        MqttProxyServer.serverChannel = ctx.channel();
        if (businessIdHex == null) {
            int businessIdInt = RandomUtils.nextInt(65535);
            businessIdHex = StringUtils.leftPad(ByteTools.int2HexStr(businessIdInt), 4, '0');
        }
        if (!MqttProxyClient.isConnect) {
            ZoomApplication.startProxyClient();
            SystemClock.sleep(1000);
            Log.e(TAG, "channelRead0: 代理没链接，先连接，再发送" );
        }

        List<SSALMessage> ssalMessageList = DefaultSSALParser.getInstance().parseReverse(msg, SSALConfigInitProperties.targetIp, SSALConfigInitProperties.targetPort, SSALConfigInitProperties.pspMACAddress, businessIdHex, UserContentTypeOctEnum.APPLICATION_DATA, FCCodeBinEnum.ONE, encryptListener);
        for (SSALMessage ssalMessage : ssalMessageList) {
            ByteBuf ssal = DefaultSSALParser.getInstance().loadSSAL(ssalMessage);
            MqttProxyClient.sendMessage(ssal);
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        Log.e(TAG, "handlerRemoved: ");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        Log.e(TAG, "handlerAdded: ");

    }
}